package com.bookmarket.utils;

//发送短信验证码

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

public class GetMsesageCode {

    private static  final String QUERY_PATH="https://api.miaodiyun.com/20150822/industrySMS/sendSMS";
    private  static final String ACCOUNT_SID="9a0b55f4937041f783a1a450c45b93be";
    private  static final String AUTH_TOKEN="eeeb2ffe8f734ae3850b12abc1b4a311";

    //根据相应手机号发送验证码
    public static String getCode(String phone) {

        String random=smsCode();
        String timestamp=getTimestamp();
        String sig=getMD5(ACCOUNT_SID,AUTH_TOKEN,timestamp);
        //短信模板
        String tamp="【郑州云和科技】验证码:"+random+",这是通往知识殿堂的钥匙，打死也不能告诉别人哦！亲!";
        //先关闭流
        OutputStreamWriter out=null;
        BufferedReader br=null;
        StringBuilder result=new StringBuilder();
        try {
            URL url=new URL(QUERY_PATH);
            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
            //因为短信接收是以post的方式，所以设置请求方式
            connection.setRequestMethod("POST");
            connection.setDoInput(true);//设置是否允许数据输入
            connection.setDoOutput(true);//设置是否允许参数输入
            connection.setConnectTimeout(5000);//设置响应时间 5秒
            connection.setReadTimeout(10000);//设置参数读取时间
            connection.setRequestProperty("Content-type","application/x-www-form-urlencoded");//设置请求头信息

            //提交请求
            out=new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            //写参数
            String args=getQueryArgs(ACCOUNT_SID,tamp,phone,timestamp,sig,"JSON");
            out.write(args);
            out.flush();//刷新方法


            //反射，java中有两个不是面向对象的，一个是 基础类型数据(但是包装类型弥补了他的缺陷)，一个是，静态成员


            //读取返回参数
            br=new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String temp="";
            while ((temp=br.readLine())!=null){//读取，读完
                result.append(temp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        //若成功，返回验证码，若失败返回00000
        JSONObject json=new JSONObject(result.toString());

        String respCode=json.getString("respCode");
        String defuatRespCode="00000";
        if (defuatRespCode.equals(respCode)){
            return random;
        }else{
            return defuatRespCode;
        }

       //return  result.toString();
    }

    //参数拼接方法
    public static String getQueryArgs(String accountSid,String smsContent,String to,String timestamp,String sig,String respDataType){
       /* accountSid=a14f6bfd43ce44c9b019de57f4e2de4b&smsContent=【秒嘀科技】您的验证码是345678，30分钟输入有效。
    &to=13896543210&timestamp=20150821100312&sig=a14f6bfd43ue44c9b019du57f4e2ee4r&respDataType=JSON
    */
       return "accountSid="+accountSid+"&smsContent="+smsContent+"&to="+to+"&timestamp="+timestamp+"&sig="+sig+"&respDataType="+respDataType;

    }


    //获取时间戳
    public static String getTimestamp(){
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    }

    //sig签名，带加密
    public static String getMD5(String sid,String token,String timestamp){
        //线程安全
        StringBuilder result=new StringBuilder();

        String source=sid+token+timestamp;
        try {
            //加密
            MessageDigest digest=MessageDigest.getInstance("MD5");
           byte[] bytes = digest.digest(source.getBytes());
           for (byte b:bytes){
               //返回十六进制，可能是一位(需要补成两位)，可能是两位
               String hex=Integer.toHexString(b&0xff);
               if(hex.length()==1){
                   result.append("0"+hex);
               }else{
                   result.append(hex);
               }
           }
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
        }

        return result.toString();
    }

    //创建 验证码
    public static String smsCode(){
        //创建随即对象
        //加“”意味着 转字符串
        String ran =new Random().nextInt(1000000)+"";
        if(ran.length()!=6){
            return smsCode();//递归
        }else{
            return ran;
        }
    }
}